<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use app\common\model\Category as CategoryModel;
use think\Controller;
use think\Request;
use fast\Tree;
use fast\Cols;
use fast\Random;

/**
 * 分类管理
 *
 * @icon fa fa-list
 * @remark 用于统一管理网站的所有分类,分类可进行无限级分类
 */
class Category extends Backend
{

    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->request->filter(['strip_tags']);
        $this->model = model('app\common\model\Category');
        $search = $this->request->get("search/a");
        if(isset($search)){
            $where = "%".$search['name']."%";
        }else{
            $where = "%%";
        }
        //print_r($where);exit;
        $tree = Tree::instance();
        $tree->init(collection($this->model->where('name','like',$where)->order('weigh desc,itemid desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v)
        {
            $categorydata[$v['itemid']] = $v;
        }
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("typeList", CategoryModel::getTypeList());
        $this->view->assign("parentList", $categorydata);
    }

    public function index(){
        $columnlist = Cols::columnread('column');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('pkey_name')){
            return $this->selectpage();
        }
        $searchfileds = array();
        $searchfileds['columnname'] = 'varcharmid';
        $searchfileds['columnenname'] = 'varcharmid';
        $searchfileds['moduleid'] = 'bigint';
        $total = count($this->categorylist);
        $result = array("total" => $total, "rows" => $this->categorylist);
        $this->view->assign("lists",$result['rows']);

        $this->view->assign("columnlist",$columnlist);
        $this->view->assign("total",$result['total']);
        return $this->view->fetch();
    }
    public function add(){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params){
                $this->modelValidate = false;
                if ($this->dataLimit){
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try{
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false){
                        //添加成功
                        $rr = model('Category')->get($params['pid']);
                        $this->model->where('itemid',$params['pid'])->update(['child' => ($rr['child']+1)]);

                        $this->success();
                    }else{
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e){
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            return $this->view->fetch();
        }
    }
    //修改
    public function edit($ids = NULL){
        $row = $this->model->get($ids);
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params){
                $this->modelValidate = false;
                if ($this->dataLimit){
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try{
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false){
                        //更新成功！
                        model('Category')->refreshChild($params['pid']);
                        $this->success();
                    }else{
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e){
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{

            $this->view->assign("row", $row);
            return $this->view->fetch();
        }
    }
    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

}
